<template>
  <div>
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">可疑识别管理系统</h1>
	            <p class="sub-title">精准记录可疑动态，及时推进排查工作，用严谨管理消除安全隐患，守护大家的生活平安</p>
	            </div>
	        </el-col>
	    </el-row>
    <el-row :gutter="20" style="margin-bottom: 15px;">
      <el-col :span="18" :offset="0">
        <el-select v-model="selectedCategory" placeholder="请选择分类" style="width: 100%;">
          <el-option label="是否处理" disabled value=""></el-option>
          <el-option label="已处理" value="已处理"></el-option>
          <el-option label="处理中" value="处理中"></el-option>
          <el-option label="未处理" value="未处理"></el-option>
        </el-select>
      </el-col>
      <el-col :span="3">
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </el-col>
      <el-col :span="3">
        <el-button type="success" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>
    
    <el-table :data="tableData.slice((currentPage-1)*pageSize, currentPage*pageSize)" border style="width: 100%"
              height="450" :row-class-name="tableRowClassName">
      <el-table-column fixed prop="infoId" label="编号" width="150" align="center">
      </el-table-column>
      <el-table-column prop="locationId" label="位置ID" width="150" align="center">
      </el-table-column>
      <el-table-column prop="status" label="处理状态" width="140" align="center">
        <template #default="{ row }">
          <el-select v-model="row.status" @change="handleStatusChange(row)" placeholder="处理状态">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="handler" label="处理人" width="150" align="center">
      </el-table-column>
      <el-table-column prop="crowdCategory" label="人群类别" align="center">
      </el-table-column>
      <el-table-column prop="recordTime" label="记录时间" align="center">
        <template #default="{ row }">
          {{ formatDateTime(row.recordTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button type="warning" icon="el-icon-edit" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <el-row type="flex" style="margin-top: 15px;">
      <el-col :push="5">
        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
                       :page-sizes="[5,10,20,50]" :page-size="pageSize" :total="tableData.length"
                       layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </el-col>
    </el-row>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="位置ID" prop="locationId">
          <el-input v-model.number="formData.locationId" placeholder="请输入位置ID"></el-input>
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择处理状态">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理人" prop="handler">
          <el-input v-model="formData.handler" placeholder="请输入处理人"></el-input>
        </el-form-item>
        <el-form-item label="人群类别" prop="crowdCategory">
          <el-select v-model="formData.crowdCategory" placeholder="请选择人群类别">
            <el-option label="老人" value="老人"></el-option>
            <el-option label="儿童" value="儿童"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog title="确认删除" v-model="deleteDialogVisible" width="30%">
      <p>确定要删除编号为 {{ deleteInfoId }} 的记录吗？</p>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, toRefs } from 'vue';
import { ElMessage } from 'element-plus';
import { post } from '@/utils/axios';

// 状态选项
const options = [
  { value: '未处理', label: '未处理' },
  { value: '处理中', label: '处理中' },
  { value: '已处理', label: '已处理' }
];

// 响应式数据
const state = reactive({
  dialogVisible: false,
  deleteDialogVisible: false,
  dialogTitle: '新增可疑信息',
  selectedCategory: '',
  currentPage: 1,
  pageSize: 5,
  tableData: [],
  deleteInfoId: '',
  formData: {
    infoId: '',
    locationId: null,
    status: '',
    handler: '',
    crowdCategory: ''
  },
  rules: {
    locationId: [
      { required: true, message: '请输入位置ID', trigger: 'blur' },
      { type: 'number', message: '位置ID必须是数字', trigger: 'blur' }
    ],
    status: [
      { required: true, message: '请选择处理状态', trigger: 'change' }
    ],
    handler: [
      { required: true, message: '请输入处理人', trigger: 'blur' }
    ],
    crowdCategory: [
      { required: true, message: '请选择人群类别', trigger: 'change' }
    ]
  }
});

// 解构响应式数据
const { 
  dialogVisible, deleteDialogVisible, dialogTitle, 
  selectedCategory, currentPage, pageSize, tableData,
  deleteInfoId, formData, rules
} = toRefs(state);

// 表单引用
const formRef = ref(null);

// 格式化日期时间
function formatDateTime(dateTime) {
  if (!dateTime) return '';
  // 处理不同格式的日期字符串
  const date = new Date(dateTime);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(',', ' ');
}

// 状态变更
function handleStatusChange(row) {
  const data = {
    infoId: row.infoId,
    status: row.status
  };
  post('/sc/suspicious/updateById', data, (res) => {
    if (res.status === 1) {
      ElMessage.success('状态更新成功！');
      getAllData(); // 重新获取数据刷新表格
    } else {
      ElMessage.error(res.message || '更新失败');
      getAllData(); // 失败时也重新获取数据以保持一致性
    }
  });
}

// 打开新增对话框
// 修改后的handleAdd方法
function handleAdd() {
  dialogTitle.value = '新增可疑信息';
  // 逐个重置表单字段
  formData.value.infoId = '';
  formData.value.locationId = null;
  formData.value.status = '';
  formData.value.handler = '';
  formData.value.crowdCategory = '';
  
  dialogVisible.value = true;
  
  // 下一次DOM更新后清除验证状态
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate();
    }
  });
}

// 打开编辑对话框
function handleEdit(row) {
  dialogTitle.value = '编辑可疑信息';
  // 复制行数据到表单
  formData.value = { ...row };
  dialogVisible.value = true;
}

// 打开删除确认对话框
function handleDelete(row) {
  deleteInfoId.value = row.infoId;
  deleteDialogVisible.value = true;
}

// 确认删除
function confirmDelete() {
  post('/sc/suspicious/deleteById', { infoId: deleteInfoId.value }, (res) => {
    if (res.status === 1) {
      ElMessage.success('删除成功！');
      deleteDialogVisible.value = false;
      getAllData(); // 重新获取数据
    } else {
      ElMessage.error(res.message || '删除失败');
    }
  });
}

// 提交表单（新增或编辑）
function handleSubmit() {
  formRef.value.validate((valid) => {
    if (valid) {
      if (formData.value.infoId) {
        // 编辑操作
        post('/sc/suspicious/updateById', formData.value, (res) => {
          if (res.status === 1) {
            ElMessage.success('更新成功！');
            dialogVisible.value = false;
            getAllData();
          } else {
            ElMessage.error(res.message || '更新失败');
          }
        });
      } else {
        // 新增操作
        post('/sc/suspicious/add', formData.value, (res) => {
          if (res.status === 1) {
            ElMessage.success('新增成功！');
            dialogVisible.value = false;
            getAllData();
          } else {
            ElMessage.error(res.message || '新增失败');
          }
        });
      }
    }
  });
}

// 表格行样式
function tableRowClassName({ row }) {
  const statusColorMap = {
    '未处理': 'red-row',
    '处理中': 'yellow-row',
  };
  return statusColorMap[row.status] || '';
}

// 分页相关
function handleSizeChange(val) {
  pageSize.value = val;
  currentPage.value = 1; // 重置为第一页
}

function handleCurrentChange(val) {
  currentPage.value = val;
}

// 搜索
function handleSearch() {
  post('/sc/suspicious/byStatus', { status: selectedCategory.value }, (res) => {
    if (res.status === 1) {
      ElMessage.success('查询成功！');
      tableData.value = res.data;
    } else {
      ElMessage.error(res.message || '未查询到数据');
      tableData.value = [];
    }
  });
}

// 获取所有数据
function getAllData() {
  post('/sc/suspicious/getAll', {}, (res) => {
    if (res.status === 1) {
      tableData.value = res.data;
    } else {
      ElMessage.error(res.message || '获取数据失败');
      tableData.value = [];
    }
  });
}

// 页面加载时获取所有数据
onMounted(() => {
  getAllData();
});
</script>

<style scoped>
/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.text-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.el-table .red-row {
  background-color: #ffdddd; /* 浅红色 */
}

.el-table .yellow-row {
  background-color: #ffffcc; /* 浅黄色 */
}

.el-row {
  margin-bottom: 10px;
}

.el-dialog__body {
  max-height: 500px;
  overflow-y: auto;
}
</style>
